import { useUserStore } from '@/store';

function checkPermission(el, binding) {
  const { value } = binding;
  const userStore = useUserStore();
  const { userInfo } = userStore;

  if (Array.isArray(value)) {
    if (value.length > 0) {
      const permissionValues = value;
      let hasPermission = true;
      for (let index = 0; index < permissionValues.length; index++) {
        hasPermission = userInfo?.roles?.includes(permissionValues[index]);
        // console.log(14, hasPermission);
        if (hasPermission) {
          break;
        }
      }
      // console.log(13, 'leads-refresh', permissionValues, hasPermission, el, el.parentNode);
      if (!hasPermission && el.parentNode) {
        el.parentNode.removeChild(el);
      }
    }
  } else {
    throw new Error(`need roles! Like v-permission="['user']"`);
  }
}

export default {
  mounted(el, binding) {
    checkPermission(el, binding);
  },
  updated(el, binding) {
    checkPermission(el, binding);
  }
};
